package Day09.dao;

import Day09.bean.Express;

import java.util.Random;

public class ExpressDao {
    private Express[][] data = new Express[10][];
    private int size;//当前存取的快递数，存快递就加一，取快递就减一
    {
        for (int i = 0; i < 10; i++) {
            data[i] = new Express[10];
        }
    }
    private Random r = new Random();

    //添加快递
    public boolean add(Express e){
        if(size == 100){
            return false;
        }
        //随机生成一个0-9的下标
        int x = -1;
        int y = -1;
        while(true){
            x = r.nextInt(10);
            y = r.nextInt(10);
            if(data[x][y] == null){//此位置无快递
                break;
            }
        }
        //取件码
        int code = randomCode();
        e.setCode(code);
        data[x][y] = e;
        return true;
    }
    //随机生成取件码方法
    private int randomCode(){
        while(true) {
            int code = r.nextInt(900000) + 100000;
            Express e = findByCode(code);
            if (e == null) {
                return code;
            }
        }
    }

    //查找单号
    public Express findByNumber(String number){
        Express e = new Express();
        e.setNumber(number);
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {
                if(e.equals(data[i][j])){
                    return data[i][j];
                }
            }
        }
        return null;
    }

    //查找取件码
    public Express findByCode(int code){
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {
                if(data[i][j] != null) {
                    if (data[i][j].getCode() == code) {
                        return data[i][j];
                    }
                }
            }
        }
        return null;
    }

    public void update(Express oldExpress,Express newExpress){
        delete(oldExpress);
        add(newExpress);
    }


    //删除快递
    public void delete(Express e){
        p:for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {
                if(e.equals(data[i][j])){
                    data[i][j] = null;
                    break p;
                }
            }
        }
    }

    public Express[][] findAll(){
        return data;
    }


}
